package com.h3c.ptability.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.ptability.cache.UserCache;
import com.h3c.ptability.dto.PtFileTemplateDTO;
import com.h3c.ptability.entity.PtFileTemplate;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.IPtFileTemplateService;
import com.h3c.ptability.service.IPtUploadFileService;
import com.h3c.ptability.utils.AppBusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (C), 2022-2022, h3c
 * FileName: PtFileTemplateController
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_file_template controller
 * Version: 1.0
 */
@Api(tags = " PtFileTemplate 接口")
@CrossOrigin
@Slf4j
@RestController
@RequestMapping(value = "/ptFileTemplate",produces = "application/json;charset=utf-8")
public class PtFileTemplateController {

    @Autowired
    CommService commService;

    @Resource
    private IPtFileTemplateService ptFileTemplateService;

    @Resource
    private IPtUploadFileService ptUploadFileService;

    /**
     * @title: queryFuzzyListForPage
     * @description: 列表分页模糊查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtFileTemplateDTO", paramType = "query"),
        @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryFuzzyListForPage", method = RequestMethod.GET)
    public Result queryFuzzyListForPage(@ModelAttribute PtFileTemplateDTO paramsDTO,
                                                            @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                            @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页模糊查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //分页
        Page page = PageHelper.startPage(currentPage, pageSize);
        //执行
        List<PtFileTemplateDTO> resultDTOList = ptFileTemplateService.selectFuzzyByDto(paramsDTO);
        PageInfo<PtFileTemplateDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(resultDTOList);
        log.info("执行列表分页模糊查询完成，准备返回的结果为：" + JSON.toJSONString(pageInfo));
        return new Result(true, 20000, "列表分页模糊查询成功", pageInfo);
    }

    /**
     * @title: queryListForPage
     * @description: 列表分页精确查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtFileTemplateDTO", paramType = "query"),
    @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
    @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryListForPage", method = RequestMethod.GET)
    public Result queryListForPage(@ModelAttribute PtFileTemplateDTO paramsDTO,
                                                       @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //分页
        Page page = PageHelper.startPage(currentPage, pageSize);
        //执行
        List<PtFileTemplateDTO> resultDTOList = ptFileTemplateService.selectFuzzyByDto(paramsDTO);
        PageInfo<PtFileTemplateDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(resultDTOList);
        log.info("执行列表分页查询完成，准备返回的结果为：" + JSON.toJSONString(pageInfo));
        return new Result(true, 20000, "列表分页查询成功", pageInfo);
    }


    /**
     * @title: save
     * @description: 数据插入
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据插入", notes = "数据插入")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtFileTemplate", paramType = "body")})
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result save(@RequestBody PtFileTemplateDTO paramsDTO) {
        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //执行
        Integer result = ptFileTemplateService.insertDto(paramsDTO);
        log.info("执行 数据插入完成，准备返回的结果为：" + JSON.toJSONString(result));
        return new Result(true, 20000, "数据插入成功", result);
    }

    /**
     * @title: update
     * @description: 数据修改
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据修改", notes = "数据修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtFileTemplate", paramType = "body")})
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(@RequestBody PtFileTemplateDTO paramsDTO) {
        log.info("准备执行 数据修改，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //执行
        Integer result = ptFileTemplateService.updateDto(paramsDTO);
        log.info("执行 数据修改完成，准备返回的结果为：" + JSON.toJSONString(result));
        return new Result(true, 20000, "数据修改成功", result);
    }

    /**
     * @title: delete
     * @description: 数据删除
     * @params: [ id ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据删除", notes = "数据删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "PtFileTemplate", paramType = "body")})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result delete(@RequestBody PtFileTemplateDTO paramsDTO) {
        log.info("准备执行 数据删除，传入的参数为：" + JSON.toJSONString(paramsDTO));
        //执行
        Integer result = ptFileTemplateService.deleteDto(paramsDTO);
        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(result));
        return new Result(true, 20000, "数据删除", result);
    }

    @GetMapping(value = "/queryTemplateByCode")
    public Result<Map<String, Object>> queryTemplateByCode(@RequestParam("templateCode") String templateCode,
                                                           @RequestParam("appId") String appId) {
        PtFileTemplate template = ptFileTemplateService.queryTemplateByCode(templateCode, appId);
        Map<String, Object> result = new HashMap<>();
        if (template != null) {
            result.put("startRow", template.getStartRow());
            result.put("startCol", template.getStartCol());
            result.put("colSize", template.getColSize());
            result.put("fieldContent", template.getFieldContent());
            result.put("file", Base64Utils.encodeToString(template.getTemplateFile()));
        } else {
            throw new AppBusinessException("找不到文件：" + templateCode + "，系统：" + appId);
        }
        return new Result<>(true, 20000, "查询成功", result);
    }


    @ApiOperation(value = "新增或修改excel模板文件", notes = "新增或修改excel模板文件")
    @PostMapping(value = "/addPtFileTemplate")
    public Result addPtFileTemplate(PtFileTemplateDTO pdFileTemplateDTO) throws UnknownHostException {
        ptFileTemplateService.addPtFileTemplate(pdFileTemplateDTO);
        // 日志
        String ip = InetAddress.getLocalHost().toString();
        ptUploadFileService.saveUploadHistory(pdFileTemplateDTO.getUploadTemplateFile(),"ptability-manage","-1", UserCache.getLoginUserId(),commService.getLoginUserNameWithNoException(),ip,pdFileTemplateDTO.getUploadTemplateFile().getOriginalFilename());
//        if( pdFileTemplateDTO.getUploadTemplateFile()!=null){
//            MultipartFile templateFile = pdFileTemplateDTO.getUploadTemplateFile();
//            commService.recordFileOperationLog(templateFile.getOriginalFilename(), templateFile.getSize(), "IMPORT");
//        }
        return new Result(true, StatusCodeEnum.ADD_SUCCESS);
    }

    /**
     * 上传文件模板返回文件id
     * @param ptFileTemplateDTO
     * @return
     * @throws UnknownHostException
     */
    @PostMapping(value = "/addPtFileTemplateReturnId")
    public Result addPtFileTemplateReturnId(PtFileTemplateDTO ptFileTemplateDTO) throws UnknownHostException {
        String fileTemplateId = ptFileTemplateService.addPtFileTemplateReturnId(ptFileTemplateDTO);
        // 日志
        String ip = InetAddress.getLocalHost().toString();
        ptUploadFileService.saveUploadHistory(ptFileTemplateDTO.getUploadTemplateFile(),"ptability-manage","-1", UserCache.getLoginUserId(),commService.getLoginUserNameWithNoException(),ip,ptFileTemplateDTO.getUploadTemplateFile().getOriginalFilename());
        return new Result(true, StatusCodeEnum.ADD_SUCCESS, fileTemplateId);
    }

    @ApiOperation(value = "删除excel模板文件", notes = "删除excel模板文件")
    @RequestMapping(value = "/deletePtFileTemplate", method = RequestMethod.POST)
    public Result deletePtFileTemplate(@RequestBody PtFileTemplateDTO pdFileTemplateDTO) {
        ptFileTemplateService.deletePtFileTemplate(pdFileTemplateDTO);
        return new Result(true, StatusCodeEnum.REMVOE_SUCCESS);
    }

    /**
     * 根据appId和模板编码获取模板对象
     * @param appId
     * @param templateCode
     * @return
     */
    @GetMapping("/getFileTemplateByCode")
    public Result<PtFileTemplate> getFileTemplateByCode(@RequestParam("appId") String appId, @RequestParam("templateCode") String templateCode){
        PtFileTemplate ptFileTemplate = ptFileTemplateService.getOne(new QueryWrapper<PtFileTemplate>().lambda()
                .eq(PtFileTemplate::getAppId, appId)
                .eq(PtFileTemplate::getTemplateCode, templateCode)
                .last("LIMIT 1"));
        return new Result<>(true, StatusCodeEnum.NORMAL, ptFileTemplate);
    }


    @ApiOperation(value = "下载excel模板文件", notes = "下载excel模板文件")
//    @PostMapping(value = "/downloadExcelTemplate")
    @RequestMapping(value = "/downloadExcelTemplate", method = RequestMethod.POST)
    public Map<String, String> downloadExcelTemplate(@RequestBody PtFileTemplateDTO pdFileTemplateDTO) {
        try {
            PtFileTemplate tempateDo = ptFileTemplateService.queryOrigFileTemplate(pdFileTemplateDTO);
            String filePath = tempateDo.getTemplateFilePath();
            String templateCode = tempateDo.getTemplateCode();
            Map<String, String> result = new HashMap<>();
            byte[] bytes = tempateDo.getOrigTemplateFile();
            String name = templateCode + (filePath.substring(filePath.lastIndexOf(".")));
            result.put("file", Base64Utils.encodeToString(bytes));
            result.put("filename", name);
            result.put("code","20000");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("文件下载异常");
        }
    }

    @ApiOperation(value = "下载excel模板文件", notes = "下载excel模板文件")
//    @PostMapping(value = "/downloadExcelTemplate")
    @RequestMapping(value = "/downloadExcelTemplateOut", method = RequestMethod.POST)
    public Map<String, String> downloadExcelTemplateOut(@RequestBody PtFileTemplateDTO pdFileTemplateDTO) {
        try {
            PtFileTemplate tempateDo = ptFileTemplateService.queryOrigFileTemplate(pdFileTemplateDTO);
            String filePath = tempateDo.getTemplateFilePath();
            String templateCode = tempateDo.getTemplateCode();
            Map<String, String> result = new HashMap<>();
            byte[] bytes = tempateDo.getTemplateFile();
            String name = templateCode + (filePath.substring(filePath.lastIndexOf(".")));
            result.put("file", Base64Utils.encodeToString(bytes));
            result.put("filename", name);
            result.put("code","20000");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("文件下载异常");
        }
    }

    /**
     * 编辑文件模板
     * @param pdFileTemplateDTO
     * @return
     */
    @PostMapping("/editExcelTemplate")
    public Result<String> editExcelTemplate(@RequestBody PtFileTemplateDTO pdFileTemplateDTO){
        ptFileTemplateService.update(new UpdateWrapper<PtFileTemplate>().lambda()
                .set(pdFileTemplateDTO.getStartCol() != null, PtFileTemplate::getStartCol, pdFileTemplateDTO.getStartCol())
                .set(pdFileTemplateDTO.getStartRow() != null, PtFileTemplate::getStartRow, pdFileTemplateDTO.getStartRow())
                .set(pdFileTemplateDTO.getColSize() != null, PtFileTemplate::getColSize, pdFileTemplateDTO.getColSize())
                .eq(PtFileTemplate::getTemplateCode, pdFileTemplateDTO.getTemplateCode())
                .eq(PtFileTemplate::getAppId, pdFileTemplateDTO.getAppId()));
        return new Result<>(true, StatusCodeEnum.NORMAL);
    }

}
